// 引入electron并创建一个Browserwindow
const { app, BrowserWindow, ipcMain, webContents } = require('electron');
const path = require('path');
const url = require('url');
const pkg = require("./package.json")
const sqlite = require('sqlite3')
const fs = require('fs')
const searchSQLite = (path) => {
  ipcMain.removeAllListeners('open-table-request', () => { })
  ipcMain.removeAllListeners('delete-table-request', () => { })
  ipcMain.removeAllListeners('edit-table-item', () => { })
  ipcMain.removeAllListeners('increase-item', () => { })
  ipcMain.removeAllListeners('delete-data-item-requset', () => { })
  ipcMain.removeAllListeners('inc-data-requset', () => { })
  const db = new sqlite.Database(path, () => {
    db.all(`select name from sqlite_master`, function (err, result) {
      mainWindow.webContents.send('data-base-name', result)
    });
    ipcMain.on('open-table-request', (event, arg) => {
      db.all(`select * from ${arg}`, (err, result) => {
        event.sender.send('open-table-response', result)
      })
    })
    ipcMain.on('delete-table-request', (event, arg) => {
      db.run(`drop table ${arg}`, (err, result) => {
        if (err) {
          console.error('删除表格错误')
        } else {
          console.error('成功删除表格')
        }
      })
    })
    ipcMain.on('edit-table-item', (event, arg) => {
      const { id, table, selectedKey, selectedValue } = arg
      db.run(`update ${table} set ${selectedKey}=${selectedValue} where id=${id}`, (err, result) => {
        if (err) {
          console.log('更新失败')
        } else {
          console.log('更新成功')
        }
      })
    })
    ipcMain.on('increase-item', (event, arg) => {
      const { table, items } = arg;
      let result = ''
      items.forEach((item, index) => {
        result += `'${item}',`
      })
      result = result.slice(0, result.length - 1)
      console.log(result)
      db.run(`insert into ${table} values(${result})`, (err, result) => {
        if (err) {
          console.log('新增数据失败')
        } else {
          console.log('新增数据成功')
        }
      })
    })
    ipcMain.on('delete-data-item-requset', (event, arg) => {
      const { table, id } = arg
      db.run(`delete from ${table} where id=${id}`, (err, result) => {
        if (err) console.log('删除错误')
        else console.log(`删除id=${id}的数据项成功`)
      })
    })
    ipcMain.on('inc-data-requset', (event, arg) => {
      let result = ''
      let count = 0
      const table = arg['sheetName']
      delete arg['sheetName']
      Object.keys(arg).forEach((item, index) => {
        if (index % 2 == 0) {
          result += `${arg[item]} `
        } else {
          result += `${parseInt(arg[item]) === 1000 ? 'text' : `char(${arg[item]})`},`
          count++
        }
      })
      result = result = result.slice(0, result.length - 1);
      console.log(result)
      db.run(`create table ${table}(id char(15),${result})`, (err, result) => {
        if (err) {
          console.log(err)
          console.log('新增表失败')
        }
        else {
          const items = new Array(count + 1).fill('lst-dd')
          let result = ''
          items.forEach((item, index) => {
            result += `'${item}',`
          })
          result = result.slice(0, result.length - 1)
          console.log(result)
          db.run(`insert into ${table} values(${result})`, (err, result) => { })
          console.log('新增表成功')
        }
      })
    })
  })
}
// 保持window对象的全局引用,避免JavaScript对象被垃圾回收时,窗口被自动关闭.
let mainWindow
try {
  const path = fs.readFileSync("./path.txt").toString()
  ipcMain.on('initial-path-request', (event, arg) => {
    event.sender.send('initial-path-response', path)
    searchSQLite(path)
  })
} catch (error) {
  console.log('未创建路径文件')
}
//记录数据库文件地址
ipcMain.on('write-path', (event, arg) => {
  fs.writeFile("./path.txt", arg, function (err) {
    if (err) {
      return console.log(err);
    } else {
      console.log("写入成功");
      searchSQLite(arg)
    }
  })

})
function createWindow () {
  //创建浏览器窗口,宽高自定义
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: false,
    }
  })
  /* 
   * 加载应用-----  electron-quick-start中默认的加载入口
   */
  if (pkg.Devtool) {
    mainWindow.webContents.openDevTools({
      mode: 'bottom'
    });
  }
  if (pkg.Dev) {
    mainWindow.loadURL('http://localhost:3000/')
  } else {
    mainWindow.loadURL(url.format({
      pathname: path.join(__dirname, './build/index.html'),
      protocol: 'file:',
      slashes: true
    }))
  }
  // 打开开发者工具，默认不打开
  // mainWindow.webContents.openDevTools()

  // 关闭window时触发下列事件.
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}
// 当 Electron 完成初始化并准备创建浏览器窗口时调用此方法
app.on('ready', createWindow)

// 所有窗口关闭时退出应用.
app.on('window-all-closed', function () {
  // macOS中除非用户按下 `Cmd + Q` 显式退出,否则应用与菜单栏始终处于活动状态.
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // macOS中点击Dock图标时没有已打开的其余应用窗口时,则通常在应用中重建一个窗口
  if (mainWindow === null) {
    createWindow()
  }
})

